<?php
class manplan {
  function __construct() {
  }

  public function listart() {
	$errcode = 0;
	$errmess = '';
    $data = array();
	
    try
    {
// Только зарегистрированные пользователи могут видеть данные
		if( !isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0 )
			throw new Exception(ERR_M::TIMEOUT_ERROR, 999);

// Find - услуга общего пользования. Поэтому, маска должна быть READ_ANY
		$rwd = $_SESSION['priv']->articles->rwd;
		if( ( $rwd & PERM_BITS::READ_ANY ) == 0 ) throw new Exception(ERR_M::DATA_OPER_DISABLED, 99);

// Открываем базу данных
		$db = App::me()->dbOpen();	

// Фильтр привилегий
		if( $rwd & PERM_BITS::READ_OTH ) $whs = '1 = 1';
		elseif( $rwd & PERM_BITS::READ_GRP ) 
			$whs = 'art_user_id IN (SELECT user_id FROM users WHERE cat_id = '.$_SESSION['cat_id'].')';
		elseif( $rwd & PERM_BITS::READ_OWN ) $whs = 'art_user_id = '.$_SESSION['user_id'];
		else $whs = '1 = 0';
		
// Формируем запрос
		$sql =  "SELECT art_id, art_code, art_full_name, met_name FROM articles ".
				"LEFT JOIN metrics ON met_id = art_met_id ".
				"WHERE ${whs} ORDER BY art_code";
		$recset = $db->query($sql);                  
        while( $row = $recset->fetch(PDO::FETCH_ASSOC) ) {
            $unit = new stdClass;
            $unit->key = $row['art_id'];
			$unit->title = $row['art_code'];
			$unit->met_name = $row['met_name'];
			$unit->description = $row['art_full_name'];
            $unit->isFolder = false;
            $unit->isLazy = false;
            $data[] = $unit;
        }
        $recset->closeCursor();
 
    }
	catch (PDOException $e) {
		$errcode = 1;
		$errmess = ERR_M::DATABASE_ERROR;
	}
    catch ( Exception $e ) {
		$errcode = $e->getCode();
		$errmess = $e->getMessage();
	}

	if( $errcode ) {
		$unit = new stdClass;
		$unit->title = '';
		$unit->errcode = $errcode;
		$unit->errmess = $errmess;
		return array($unit);
	}
	else return $data;
  }

  
  public function report() {
    $data = new stdClass;
	$data->errcode = 0;
	$data->errmess = '';
	$data->article = array();
	$data->unit = array();
	
    $art_ids	= isset($_POST['art_ids']) ? $_POST['art_ids'] : '';
    $art_num	= isset($_POST['art_num']) ? $_POST['art_num'] : '';

    try
    {
// Только зарегистрированные пользователи могут видеть данные
		if( !isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0 )
			throw new Exception(ERR_M::TIMEOUT_ERROR, 999);

// Проверяем данные
		if( !is_array($art_ids) || !Tools::is_numeric_array($art_ids)  ||
			!is_array($art_num)  || !Tools::is_numeric_array($art_num) ||
			count( $art_ids ) != count( $art_num ) )
			throw new Exception(ERR_M::PROTOCOL_ERROR, 1);

// Есть ли какие-либо права на чтение
		$rwd_art = $_SESSION['priv']->articles->rwd;
		if( ( $rwd_art & PERM_BITS::READ_ANY ) == 0 ) throw new Exception(ERR_M::DATA_OPER_DISABLED, 99);

		$rwd_uni = $_SESSION['priv']->units->rwd;
		if( ( $rwd_uni & PERM_BITS::READ_ANY ) == 0 ) throw new Exception(ERR_M::DATA_OPER_DISABLED, 99);

// Открываем базу данных
		$db = App::me()->dbOpen();	

//
//  Формируем список изделий
// 

// Фильтр привилегий
		$whs = array();
		if( $rwd_art & PERM_BITS::READ_OTH ) $whs[] = '1 = 1';
		elseif( $rwd_art & PERM_BITS::READ_GRP ) 
			$whs[] = 'art_user_id IN (SELECT user_id FROM users WHERE cat_id = '.$_SESSION['cat_id'].')';
		elseif( $rwd_art & PERM_BITS::READ_OWN ) $whs[] = 'art_user_id = '.$_SESSION['user_id'];
		else $whs[] = '1 = 0';
		$whs[] = 'art_id IN ('.implode(',', $art_ids).')';
		
		$where = implode(' AND ', $whs);
		
// Формируем запрос
		$sql =	"SELECT art_id, art_code, art_full_name, met_name FROM articles ".
				"LEFT JOIN metrics ON met_id = art_met_id ".
				"WHERE ${where} ORDER BY art_code";
		$rs = $db->query($sql);
        while( $row = $rs->fetch(PDO::FETCH_ASSOC) ) {
            $unit = new stdClass;
			$unit->code = $row['art_code'];
			$unit->descr = $row['art_full_name'];
			$unit->met_name = $row['met_name'];;
			$i = array_search( $row['art_id'], $art_ids );
			$unit->amount = is_bool($i) ? '' : $art_num[$i];
            $data->article[] = $unit;
        }
        $rs->closeCursor();
 
//
//  Формируем список материалов
// 
		
		for( $k=0; $k<count($art_ids); $k++ ) {
			$art_id = $art_ids[$k];
			$quont = floatval($art_num[$k]);

			if( ! $quont ) continue;
			
			$sql =	'SELECT spm_uni_id, spm_amount, uni_name, uni_full, uni_met_id, uni_met_opt_id, uni_met_mul, '.
							'met.met_name AS met_name, opt.met_name AS opt_met_name '.
					'FROM specmodel AS spm '.
					'INNER JOIN units AS uni ON uni.uni_id = spm.spm_uni_id '.
					'INNER JOIN metrics AS met ON met.met_id = uni.uni_met_id '.
					'LEFT  JOIN metrics AS opt ON opt.met_id = uni.uni_met_opt_id '.
					'WHERE spm_art_id = '.$art_id.' ORDER BY uni_name';
			
			$rs = $db->query($sql);
			while( $row = $rs->fetchObject() ) {
				$idx = -1;
				for( $i=0; $i<count($data->unit); $i++ ) {
					if( $data->unit[$i]->id == $row->spm_uni_id ) {
						$idx = $i; break;
					}
				}
				if( $idx < 0 ) {
					$unit = new stdClass;
					$unit->id = $row->spm_uni_id;
					$unit->code = $row->uni_name;
					$unit->descr = $row->uni_full;
				
					$unit->amount = $quont * $row->spm_amount;
					$unit->opt_amount = 0;
					$unit->met_id = $row->uni_met_id;
					$unit->met_name = $row->met_name;
					
					$unit->opt_met_id = 0;
					$unit->opt_met_name = '';
					$unit->met_mul = 0;
				
					if( $row->uni_met_opt_id ) {
						$unit->opt_met_id = $row->uni_met_opt_id;
						$unit->opt_met_name = $row->opt_met_name;
						$unit->met_mul = floatval($row->uni_met_mul);
					}
					$data->unit[] = $unit;
				}
				else {
					$data->unit[$idx]->amount += $quont * $row->spm_amount;
				}
			}
			$rs->closeCursor();
		}

// Перещитываем доп.метрику там, где она есть, обнуляем величины склада	и дефицита
		for( $k=0; $k<count($data->unit); $k++ ) {
			if( $data->unit[$k]->met_mul ) {
				$data->unit[$k]->opt_amount = $data->unit[$k]->amount / $data->unit[$k]->met_mul;
			}
			$data->unit[$k]->stock = 0;
			$data->unit[$k]->opt_stock = 0;
			$data->unit[$k]->diff = 0;
			$data->unit[$k]->opt_diff = 0;
		}
		
// Ищем, что есть на складе
		for( $k=0; $k<count($data->unit); $k++ ) {
			$uni_id = $data->unit[$k]->id;
			$sql =	"SELECT sto_id, sto_remain, sto_metric FROM stock WHERE sto_uni_id = ${uni_id} AND sto_retire_date IS NULL";
			$amount = 0;
			$opt_amount = 0;
			$rs = $db->query($sql);
			while( $row = $rs->fetchObject() ) {
				if( $row->sto_metric == $data->unit[$k]->opt_met_id ) {
					$opt_amount = $row->sto_remain;
					$amount = $row->sto_remain * $data->unit[$k]->met_mul;
				}
				elseif( $row->sto_metric == $data->unit[$k]->met_id ) {
					$amount = $row->sto_remain;
					if( $data->unit[$k]->opt_met_id )
						$opt_amount = $row->sto_remain / $data->unit[$k]->met_mul;
					else
						$opt_amount = 0;
				}
				else 
					throw new Exception( "Ошибка приведения метрик для позиции '".
							$row->sto_id."' склада. Обратитесь к администратору системы", 1);
				
				$data->unit[$k]->stock += $amount;
				$data->unit[$k]->opt_stock += $opt_amount;
			}
			$data->unit[$k]->diff = $data->unit[$k]->amount - $data->unit[$k]->stock;
			$data->unit[$k]->opt_diff = $data->unit[$k]->opt_amount - $data->unit[$k]->opt_stock;			
		}
    }
	catch (PDOException $e) {
		$data->errcode = 1;
		$data->errmess = ERR_M::DATABASE_ERROR;
	}
    catch ( Exception $e ) {
		$data->errcode = $e->getCode();
		$data->errmess = $e->getMessage();
	}

	return $data;
  }
  

} // End of manplan class
?>